// 云函数 - 更新订单状态
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { orderId, status, skipReview } = event

  try {
    // 验证参数
    if (!orderId) {
      return {
        success: false,
        message: '订单ID不能为空'
      }
    }

    if (!status) {
      return {
        success: false,
        message: '状态不能为空'
      }
    }

    // 获取当前用户信息
    const userOpenid = wxContext.OPENID
    if (!userOpenid) {
      return {
        success: false,
        message: '用户未登录'
      }
    }

    // 查询订单详情，验证用户权限
    const orderResult = await db.collection('orders').doc(orderId).get()
    
    if (!orderResult.data) {
      return {
        success: false,
        message: '订单不存在'
      }
    }

    const orderData = orderResult.data
    
    // 验证订单是否属于当前用户
    if (orderData.userId !== userOpenid) {
      return {
        success: false,
        message: '无权限更新此订单'
      }
    }

    // 如果是跳过评价操作，验证订单状态
    if (skipReview && orderData.status !== 'pending_review') {
      return {
        success: false,
        message: '订单状态异常，无法跳过评价'
      }
    }

    // 更新订单状态
    const updateData = {
      status: status,
      updateTime: new Date()
    }

    const result = await db.collection('orders').doc(orderId).update({
      data: updateData
    })

    if (result.stats && result.stats.updated > 0) {
      return {
        success: true,
        message: '订单状态更新成功',
        orderId: orderId,
        newStatus: status
      }
    } else {
      return {
        success: false,
        message: '订单更新失败'
      }
    }

  } catch (error) {
    console.error('更新订单状态失败:', error)
    return {
      success: false,
      message: `更新失败: ${error.message}`
    }
  }
}